﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace cube
{
    public partial class userAccount : Form
    {
        /// <summary>
        /// Event wenn sich ein User eingeloggt hat
        /// </summary>
        public event EventHandler<userEventArgs> UserLogedIn;

        #region benötigte Variablen
        private userAccountControl activeControl;
        private List<String[]> userAccounts = new List<string[]>();
        private String m_User;
        private int m_UserLevel;
        private String[] userData;
        #endregion

        /// <summary>
        /// Konstruktor mit Infos zum eingeloggten User.GUI wird abh. vom Userlevel angepasst und die Account-Liste erstellt
        /// </summary>
        /// <param name="user"></param>
        /// <param name="userLevel"></param>
        public userAccount(String user, int userLevel)
        {
            InitializeComponent();
            m_User = user;
            m_UserLevel = userLevel;

            GuiToUserlevel();
            UpdateUserAccountList();
        }
        /// <summary>
        /// GUI wird abh. vom Userlevel angepasst
        /// </summary>
        private void GuiToUserlevel()
        {
            if (m_UserLevel == 1)
            {
                groupBox_CreateNewUser.Visible = true;
                Button_userAccountDelete.Enabled = true;
            }

            else
            {
                groupBox_CreateNewUser.Visible = false;
                Button_userAccountDelete.Enabled = false;
            }
        }
        /// <summary>
        /// Hier wird das Event gefeuert wenn sich ein User eingeloggt hat
        /// </summary>
        /// <param name="user"></param>
        /// <param name="userLevel"></param>
        protected virtual void OnUserDataReceived(String user, int userLevel)
        {
            EventHandler<userEventArgs> userLogedIn = this.UserLogedIn;
            if (userLogedIn != null)
            {
                m_User = user;
                m_UserLevel = userLevel;
                userLogedIn(this, new userEventArgs(user, userLevel));
                if (userLevel == 1)
                {
                    button_createNewUser.Enabled = true;
                    groupBox_CreateNewUser.Visible = true;
                }
                else
                {
                    button_createNewUser.Enabled = false;
                    groupBox_CreateNewUser.Visible = false;
                }
            }
        }
        /// <summary>
        /// Login des Users wenn die eingegebenen Daten ok sind
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_login_Click(object sender, EventArgs e)
        {
            try
            {
                if (checkUserData(textBox_username.Text, textBox_password_login.Text))
                {
                    OnUserDataReceived(textBox_username.Text, Convert.ToInt32(userData[1]));
                    statusStrip1.BackColor = Color.Green;
                    statusLabel.Text = Properties.Resources.UserString + " " + textBox_username.Text + " " + Properties.Resources.LoginString;
                    textBox_username.Text = "";
                    textBox_password_login.Text = "";
                    GuiToUserlevel();
                    UpdateUserAccountList();
                }
                else
                {
                    statusStrip1.BackColor = Color.Red;
                    textBox_password_login.Text = "";
                    statusLabel.Text = Properties.Resources.LoginincorrectString;
                }
            }
            catch { }
        }
        /// <summary>
        /// Prüft die registry auf die übergebenen Userdaten
        /// </summary>
        /// <param name="user"></param>
        /// <param name="pw"></param>
        /// <returns></returns>
        private bool checkUserData(String user, String pw)
        {
            String loginPW;

            try
            {
                userData = registryUserData.getUserData(user);
                if ((userData[0] != "") && (userData[1] != ""))
                {
                    loginPW = md5Encrypter.CreateMD5(pw);
                    if (userData[0] == loginPW)
                        return true;
                    else
                        return false;
                }
                else
                    return false;
            }
            catch { return false; }
        }
        /// <summary>
        /// Erstellen eines neuen User-Accounts
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_createNewUser_Click(object sender, EventArgs e)
        {
            try
            {
                if (textBox_NewUserPassword1.Text == textBox_NewUserPassword2.Text)
                {
                    registryUserData.insertUserData(textBox_NewUser.Text, md5Encrypter.CreateMD5(textBox_NewUserPassword1.Text), comboBox_userLevel.Text);
                    statusStrip1.BackColor = Color.Green;
                    statusLabel.Text = Properties.Resources.NewUserString + " " + textBox_NewUser.Text + " " + Properties.Resources.CreatedString;
                    UpdateUserAccountList();
                }
                else
                {
                    statusStrip1.BackColor = Color.Red;
                    statusLabel.Text = Properties.Resources.CantCreateUserString;
                }
            }
            catch { }
        }

        private void userAccount_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }
        /// <summary>
        /// Textboxen werden geleert
        /// </summary>
        public void clearText()
        {
            textBox_username.Text = "";
            textBox_password_login.Text = "";
            textBox_NewUser.Text = "";
            textBox_NewUserPassword1.Text = "";
            textBox_NewUserPassword2.Text = "";
            comboBox_userLevel.Text = "1";

            statusStrip1.BackColor = this.BackColor;
            statusLabel.Text = "Status:";
        }
        /// <summary>
        /// Accounts werden aus der registry ausgelesen und in der Account-Liste dargestellt
        /// </summary>
        private void UpdateUserAccountList()
        {
            //--------------------------------------------------
            //User Accounts anzeigen lassen...
            //--------------------------------------------------
            try
            {
                flowLayoutPanel_UserAccounts.Controls.Clear();
                userAccounts.Clear();
                userAccounts = registryUserData.getAllUsers();
                for (int i = 0; i < userAccounts.Count; i++)
                {
                    userAccountControl newAccount = new userAccountControl();
                    newAccount.UserName = userAccounts[i][0];
                    newAccount.UserLevel = userAccounts[i][1];
                    newAccount.pictureBox_UserImg.MouseClick += new System.Windows.Forms.MouseEventHandler(this.Control_MouseClick);
                    switch (Convert.ToInt32(newAccount.UserLevel))
                    {
                        case 1: newAccount.UserImage = Properties.Resources.userlevel1;
                            break;
                        case 2: newAccount.UserImage = Properties.Resources.userlevel2;
                            break;
                        case 3: newAccount.UserImage = Properties.Resources.userlevel3;
                            break;
                        default: break;
                    }
                    if (newAccount.UserName == m_User)
                    {
                        newAccount.BorderStyle = BorderStyle.Fixed3D;
                        activeControl = newAccount;
                        textBox_username.Text = activeControl.UserName;
                    }
                    flowLayoutPanel_UserAccounts.Controls.Add(newAccount);

                }
                flowLayoutPanel_UserAccounts.Update();
            }
            catch { }
        }
        /// <summary>
        /// Wenn ein Account-Item angeklickt wurde den entsprechenden Usernamen in die vorgesehene Textbox automatisch reinkopieren
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Control_MouseClick(Object sender, EventArgs e)
        {
            foreach (userAccountControl control in flowLayoutPanel_UserAccounts.Controls)
            {
                control.BorderStyle = System.Windows.Forms.BorderStyle.None;
            }
            ((sender as PictureBox).Parent as userAccountControl).BorderStyle = BorderStyle.Fixed3D;
            activeControl = ((sender as PictureBox).Parent as userAccountControl);

            textBox_username.Text = activeControl.UserName;
        }
        /// <summary>
        /// Löschen eines User-Accounts. Der angemeldete User, vorausgesetzt er hat Adminrechte, kann sich auch selbst löschen. Falls kein
        /// Admin mehr übrig ist, wird beim nächsten Neustart des Programms ein neuer Admin-Account erstellt
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_userAccountDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(Properties.Resources.DeleteAccString + ": " + activeControl.UserName + " ?", Properties.Resources.DeleteAccHeader, MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                //Account aus Registry löschen
                registryUserData.deleteUserData(activeControl.UserName);
                //Wenn sich der User selbst löscht, m_User zurücksetzen
                if (activeControl.UserName == m_User)
                {
                    m_User = "No User";
                    m_UserLevel = 3;
                    statusStrip1.BackColor = Color.Yellow;
                    statusLabel.Text = Properties.Resources.NoUserString;
                    OnUserDataReceived(m_User, m_UserLevel);

                }
                UpdateUserAccountList();
            }
        }
    }
}
